package com.seckill.dis.goods.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.seckill.dis.common.api.goods.GoodsServiceApi;
import com.seckill.dis.common.api.goods.vo.GoodsVo;
import com.seckill.dis.common.api.seckill.vo.SeckillGoodsVO;
import com.seckill.dis.common.domain.Goods;
import com.seckill.dis.common.domain.SeckillGoods;
import com.seckill.dis.common.result.Result;
import com.seckill.dis.goods.persistence.GoodsMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;

import java.util.List;

/**
 * 商品服务接口实现
 *
 * @author noodle
 */
@Service(interfaceClass = GoodsServiceApi.class)
public class GoodsServiceImpl implements GoodsServiceApi {

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public List<GoodsVo> listGoodsVo() {
        return goodsMapper.listGoodsVo();
    }

    @Override
    public GoodsVo getGoodsVoByGoodsId(long goodsId) {
        return goodsMapper.getGoodsVoByGoodsId(goodsId);
    }

    /**
     * 通过商品的id查出商品的所有信息（包含该商品的秒杀信息）
     *
     * @param goodsId
     * @return
     */
    @Override
    public GoodsVo getGoodsVoByGoodsId(Long goodsId) {
        return goodsMapper.getGoodsVoByGoodsId(goodsId);
    }


    /**
     * 减库存
     *
     * @param goods
     * @return
     */
    @Override
    public boolean reduceStock(GoodsVo goods) {
        SeckillGoods seckillGoods = new SeckillGoods();
        //秒杀商品的id和商品的id是一样的
        seckillGoods.setGoodsId(goods.getId());
        int ret = goodsMapper.reduceStack(seckillGoods);
        return ret > 0;
    }

    /**
     * 新增商品
     * @param goodsVO
     * @return
     */
    @Override
    public Result<?> addGoods(GoodsVo goodsVO) {

        //id, goods_name, goods_title, goods_img, goods_detail, goods_price, goods_stock
        //生成雪花ID，
        Goods goods = new Goods();
        BeanCopier copier = BeanCopier.create(GoodsVo.class, Goods.class,false);
        copier.copy(goodsVO, goods,null);

        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        goods.setId(snowflake.nextId());

        return Result.success(goodsMapper.addGoods(goods));
    }

    /**
     * 新增秒杀活动
     * @param seckillGoodsVO
     * @return
     */
    @Override
    public Result<?> insertSeckill(SeckillGoodsVO seckillGoodsVO) {
        SeckillGoods seckillGoods = new SeckillGoods();
        BeanCopier copier = BeanCopier.create(SeckillGoodsVO.class, SeckillGoods.class,false);
        copier.copy(seckillGoodsVO, seckillGoods,null);
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        seckillGoods.setId(snowflake.nextId());

        return Result.success(goodsMapper.insertSeckill(seckillGoods));
    }
}
